import { userLoginAPI ,Loginfo,LoginOut,getPass} from '@/api/login'
import { getToken, setToken, clearToken } from '@/lib/ulit'
import router, { routerReset } from '@/router'
export default{
    namespaced : true,
    state :{
       code : '',
       name : '',
       role: '',
       isShow : '',
       asyncURL:''
    },
    mutations:{
        set_code :(state, params) => state.code = params,
        set_name :(state, params) => state.name = params,
        set_role: (state, params) => state.role = params,//角色
        set_show: (state, params) => state.isShow = params,//按钮  （ 普通用户
        // set_asyncURL: (state, params) => state.asyncURL = params
    },
    actions :{
        //登录
        login({commit},{username,password,code}){
            return new Promise((resolve,reject)=>{
                userLoginAPI({username,password,code}).then(res=>{
                    if(res.code == 1){ // 正常请求
                        commit('set_code',res.code)
                        commit('set_role', res.data)
                        
                        if(res.data == 'staff'){
                            commit('set_show', false)
                        }else{
                            commit('set_show', true)
                        }

                        setToken(res.code)
                    }
                    resolve(res)
                }).catch(err=>reject(err))
            })
        },
        getUserInfo ({ commit }) {
            return new Promise((resolve, reject) => {
                Loginfo().then(res => {
                commit('set_name', res) //实际
                resolve(res)
              }).catch(err => {
                reject(err)
              })
            })
          },
          logout ({ commit }) {
            return new Promise((resolve,reject)=>{
                LoginOut().then(res=>{
                    if(res.code == '1'){//mock要注释掉 连接服务放开
                        clearToken()
                        // 清空本地缓存
                        localStorage.clear();
                        console.log(localStorage.state);
                         // 跳转
                        router.replace('/login')
                        // 重新刷新页面 重置vuex 和 路由配置
                        routerReset()// 重置路由
                        // 清楚角色信息
                        commit('set_role', '')
                        commit('set_name', '')
                    }
                    console.log(res,'ascasc');

            resolve(res)
                }).catch(err=>reject(err))
            })
          }

    }
}
